package com.longmao.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.longmao.commonutils.JwtUtils;
import com.longmao.commonutils.R;
import com.longmao.commonutils.ordervo.UcenterMemberOrder;
import com.longmao.eduservice.client.UcenterClient;
import com.longmao.eduservice.entity.EduComment;
import com.longmao.eduservice.service.EduCommentService;
import com.longmao.servicebase.handler.LongMaoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author longmao
 * @since 2022-02-25
 */
@RestController
//@CrossOrigin
@RequestMapping("/eduservice/comment")
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    //根据课程id_分页查询课程评论的方法
    @GetMapping("/getCommentPage/{page}/{limit}/{courseId}")
    public R getCommentPage(@PathVariable Long page, @PathVariable Long limit,@PathVariable String courseId){
        Page<EduComment> commentPage = new Page<>(page, limit);

        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();

        //判断课程id是否为空
        if (!StringUtils.isEmpty(courseId)){
            wrapper.eq("course_id",courseId);
        }

        //按最新排序
        wrapper.orderByDesc("gmt_create");

        //数据会被封装到commentPage中
        commentService.page(commentPage,wrapper);

        List<EduComment> commentList = commentPage.getRecords();

        HashMap<String, Object> map = new HashMap<>();
        map.put("current",commentPage.getCurrent());
        map.put("size",commentPage.getSize());
        map.put("total",commentPage.getTotal());
        map.put("pages",commentPage.getPages());
        map.put("hasPrevious",commentPage.hasPrevious());
        map.put("hasNext",commentPage.hasNext());
        map.put("list",commentList);

        return R.ok().data(map);
    }

    //添加评论
    @PostMapping("/auth/addComment")
    public R addComment(HttpServletRequest request, @RequestBody EduComment eduComment){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //判断用户是否登录
        if (StringUtils.isEmpty(memberId)){
            throw new LongMaoException(20001,"请先登录");
        }
        eduComment.setMemberId(memberId);

        //远程调用ucenter根据用户id获取用户信息
        UcenterMemberOrder memberVo = ucenterClient.getMemberInfoById(memberId);

        eduComment.setAvatar(memberVo.getAvatar());
        eduComment.setNickname(memberVo.getNickname());

        //保存评论
        commentService.save(eduComment);

        return R.ok();
    }
}

